﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;

namespace CodeAuto.Pages
{
    public partial class TotalProject : System.Web.UI.Page
    {
        private static object obj = new object();
        Models.T_Project project = null;
        List<Models.T_Table> lists = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            DavidDB.ADO.DBManager db = new DavidDB.ADO.DBManager();
            int productid = Convert.ToInt32(Request.QueryString["productid"]);
            project = new Models.T_Project();
            project.Id = productid;
            project = db.GetModel(project);

            Models.T_Table table = new Models.T_Table();
            table.ProjectId = project.Id;
            var tables = db.GetSomeObject(table);

            List<string> Models = new List<string>();
            List<string> Interfaces = new List<string>();
            List<string> Impls = new List<string>();
            lists = new List<Models.T_Table>();
            foreach (Models.T_Table t in tables)
            {
                Models.T_Field field = new Models.T_Field();
                field.TableId = t.Id;
                var fields = db.GetSomeObject(field);
                List<Models.T_Field> _fields = new List<Models.T_Field>();
                foreach (Models.T_Field f in fields)
                {
                    _fields.Add(f);
                }
                Models.Add(DALS.FileDALS.GetModelString(project, t, _fields));
                Interfaces.Add(DALS.FileDALS.GetInterfaceString(project, t));
                Impls.Add(DALS.FileDALS.GetImplString(project, t));
                lists.Add(t);
            }
            for (int i = 0; i < tables.Count; i++)
            {
                CreateFile(tables[i].TableName + ".cs", Models[i], project.ProjectName, 1);
                CreateFile("I" + tables[i].TableName + ".cs", Interfaces[i], project.ProjectName, 2);
                CreateFile("Impl" + tables[i].TableName + ".cs", Impls[i], project.ProjectName, 3);
            }

            string modelcsproject = DALS.CsprojDALS.GetCsproject(project.ProjectName, lists, 1, project.Id);
            string interfacecsproject = DALS.CsprojDALS.GetCsproject(project.ProjectName, lists, 2, project.Id);
            string implcsproject = DALS.CsprojDALS.GetCsproject(project.ProjectName, lists, 3, project.Id);

            CreateFile(project.ProjectName + ".Models.csproj", modelcsproject, project.ProjectName, 1);
            CreateFile(project.ProjectName + ".Interfaces.csproj", interfacecsproject, project.ProjectName, 2);
            CreateFile(project.ProjectName + ".Impls.csproj", implcsproject, project.ProjectName, 3);

            string projectString = DALS.ProductDAL.GetProductString(project.Id, project.ProjectName);
            string directoryPath = AppDomain.CurrentDomain.BaseDirectory + "/Product/" + project.ProjectName;

            WriteFile(directoryPath + "/" + project.ProjectName + ".sln", projectString);

            CreateDB(db);
            AddAdminPages(db);
            db.Commit();
            db.Dispose();
        }

        private void AddAdminPages(DavidDB.ADO.DBManager db)
        {
            string directoryPath = AppDomain.CurrentDomain.BaseDirectory + "/Product/" + project.ProjectName + "/" + project.ProjectName + "/Admin";
            if (!System.IO.Directory.Exists(directoryPath))
            {
                System.IO.Directory.CreateDirectory(directoryPath);
            }
            directoryPath = AppDomain.CurrentDomain.BaseDirectory + "/Product/" + project.ProjectName + "/" + project.ProjectName + "/Content/";
            if (!System.IO.Directory.Exists(directoryPath))
            {
                System.IO.Directory.CreateDirectory(directoryPath);
            }
            DALS.IO.CopyFiles(AppDomain.CurrentDomain.BaseDirectory + "/Tempto/admin", directoryPath, true);
        }

        private void CreateDB(DavidDB.ADO.DBManager db)
        {
            string directoryPath = AppDomain.CurrentDomain.BaseDirectory + "/Product/" + project.ProjectName + "/" + project.ProjectName;
            if (!System.IO.Directory.Exists(directoryPath))
            {
                System.IO.Directory.CreateDirectory(directoryPath);
            }
            string file = directoryPath + "/" + project.ProjectName + ".mdb";
            if (System.IO.File.Exists(file))
            {
                System.IO.File.Delete(file);
            }
            System.IO.File.Copy(AppDomain.CurrentDomain.BaseDirectory + "/Tempto/demo.mdb", file);
            foreach (Models.T_Table table in lists)
            {
                Models.T_Field field = new Models.T_Field();
                field.TableId = table.Id;
                var query = db.GetSomeObject(field);
                List<Models.T_Field> fields = new List<Models.T_Field>();
                foreach (Models.T_Field f in query)
                {
                    fields.Add(f);
                }
                fields = fields.OrderBy(a => a.Id).ToList();
                string sql = DALS.SQLDALS.GetAccessString(table, fields).Replace("<br/>", "");
                //string baseDBString = DavidDB.ADO.Tools.AccessHelper.connectionString;
                //DavidDB.ADO.Tools.AccessHelper.connectionString = DavidDB.ADO.Tools.AccessHelper.connectionString.Replace("CodeAuto.mdb", "/Product/" + project.ProjectName + "/" + project.ProjectName + "/" + project.ProjectName + ".mdb");
                //db.ExecuteScalar(sql);
                //DavidDB.ADO.Tools.AccessHelper.connectionString = baseDBString;
                string connectingString = DavidDB.ADO.Tools.AccessHelper.connectionString.Replace("CodeAuto.mdb", "/Product/" + project.ProjectName + "/" + project.ProjectName + "/" + project.ProjectName + ".mdb");
                OleDbConnection connection = new OleDbConnection(connectingString);
                connection.Open();
                OleDbCommand cmd = new OleDbCommand(sql);
                cmd.Connection = connection;
                int val = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                cmd.Dispose();
                connection.Close();
                connection.Dispose();
            }

        }

        private void CreateFile(string name, string content, string productName, int fileType)
        {
            string directoryPath = AppDomain.CurrentDomain.BaseDirectory + "/Product/" + productName;
            string filepath = "";
            if (fileType == 1)
            {
                filepath = directoryPath + "/" + productName + ".Models";
            }
            else if (fileType == 2)
            {
                filepath = directoryPath + "/" + productName + ".Interfaces";
            }
            else
            {
                filepath = directoryPath + "/" + productName + ".Impls";
            }
            if (!System.IO.Directory.Exists(directoryPath))
            {
                System.IO.Directory.CreateDirectory(directoryPath);
            }
            if (!string.IsNullOrEmpty(filepath))
            {
                System.IO.Directory.CreateDirectory(filepath);
            }
            WriteFile(filepath + "/" + name, content);


            filepath += "/Properties";
            if (!System.IO.Directory.Exists(filepath))
            {
                System.IO.Directory.CreateDirectory(filepath);
            }

            string assemblyString = DALS.AssemblyDAL.GetAssemblyFile(project.Id, project.ProjectName, project.Description, fileType);
            WriteFile(filepath + "/AssemblyInfo.cs", assemblyString);
        }


        /// <summary>
        ///  创建一个TXT文件
        /// </summary>
        /// <param name="FILE_NAME">文件路径</param>
        /// <param name="str">内容</param>
        public static void WriteFile(string FILE_NAME, string str)
        {

            lock (obj)
            {
                if (System.IO.File.Exists(FILE_NAME))
                {
                    System.IO.File.Delete(FILE_NAME);
                }
                System.IO.StreamWriter sw = null;
                sw = System.IO.File.AppendText(FILE_NAME);
                sw.WriteLine(str);

                sw.Flush();
                sw.Close();
            }
        }
    }
}